package com.example.module_motocircle.ui.search

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.lib_common.base.BaseViewModel
import com.example.lib_common.base.state.Empty
import com.example.lib_common.base.state.Failed
import com.example.lib_common.base.state.Loading
import com.example.lib_common.base.state.RequestEvent
import com.example.lib_common.base.state.Success
import com.example.lib_storage.mmkv.AppMMKV
import com.example.lib_storage.mmkv.utils.GSON
import com.example.module_motocircle.model.HotListItem
import com.example.module_motocircle.model.HotListType
import com.example.module_motocircle.model.SearchSuggestionModel
import com.example.module_motocircle.model.Topic1
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class SearchViewModel @Inject constructor(private val mRepository: SearchRepository) :
    BaseViewModel() {
//    /*
//    获得搜索关键字列表
//     */
//    private val mSearchKeyWord_ = MutableSharedFlow<RequestEvent>()
//    val mSearchKeyWord = mSearchKeyWord_.asSharedFlow()
//    var mSearchKeyWordLiveData =listOf<SearchKeyWordEntity>()
//
//        fun searchKeyWordList(keyWord: String) {
//        execute(
//            action = repository.searchKeyWordList(keyWord),
//            onStart = {
//                mSearchKeyWord_.emit(Loading)
//            },
//            onError = {
//                mSearchKeyWord_.emit(Failed(it))
//            },
//            onFinish = {
//               if (it.data.isNullOrEmpty()){
//                   mSearchKeyWord_.emit(Empty)
//               }else{
//                   mSearchKeyWordLiveData  = it.data
//                   mSearchKeyWord_.emit(Success)
//               }
//            }
//        )
//    }

    companion object {
        private const val DEFAULT_SEARCH_HISTORY_NUM = 10
    }

    //搜索关键词
    val mKeywords = MutableStateFlow("")

    //历史数据
    val mSearchHistoryData = MutableStateFlow<List<String>>(listOf())

    private var _searchHoTDataEvent = MutableStateFlow<RequestEvent>(Loading)
    var mSearchHotDataEvent = _searchHoTDataEvent.asStateFlow()

    var mHotTopic = listOf<HotListItem>()
    var mHotPost = listOf<HotListItem>()
    var mHotArticle = listOf<HotListItem>()
    var mHotInformation = listOf<HotListItem>()

    var mSuggestionList = mutableListOf<SearchSuggestionModel>()

    private val _searchSuggestionEvent = MutableStateFlow<RequestEvent>(Loading)
    val mSearchSuggestionEvent = _searchSuggestionEvent.asStateFlow()

    //获取历史数据
    fun getSearchHistory() {
//        viewModelScope.launch(Dispatchers.IO) {
//            if (AppMMKV.searchHistory.isNotEmpty()) {
//                val historyList = GSON.fromJson<List<String>>(AppMMKV.searchHistory) ?: listOf()
//                //倒序
//                mSearchHistoryData.emit(historyList.reversed())
//            }
//        }
    }

    fun isHistoryEmpty(): Boolean {
        //return (GSON.fromJson<List<String>>(AppMMKV.searchHistory) ?: listOf()).isEmpty()
        return false
    }

    //添加历史数据
    fun addSearchHistory(content: String) {
//        viewModelScope.launch(Dispatchers.IO) {
//            val historyList = GSON.fromJson<MutableList<String>>(AppMMKV.searchHistory) ?: mutableListOf()
//            val isContains = historyList.contains(content)
//            //不操作
//            if (isContains && historyList.indexOf(content) == historyList.lastIndex) {
//                return@launch
//            }
//            //移除记录
//            if (historyList.size >= DEFAULT_SEARCH_HISTORY_NUM) {
//                if (!isContains)
//                    historyList.removeAt(0)
//                else
//                    historyList.removeAt(historyList.indexOf(content))
//            } else {
//                if (isContains)
//                    historyList.removeAt(historyList.indexOf(content))
//            }
//            //添加记录
//            historyList.add(content)
//            //保存
//            AppMMKV.searchHistory = GSON.toJson(historyList)
//            //通知更新
//            mSearchHistoryData.emit(historyList.reversed())
//        }
    }

    //清空历史数据
    fun clearSearchHistory() {
//        viewModelScope.launch(Dispatchers.IO) {
//            AppMMKV.searchHistory = ""
//            mSearchHistoryData.emit(listOf())
//        }
    }

    //获取热门搜索数据
    fun getSearchHotData() {
        execute(
            action = mRepository.getSearchHotData(),
            onStart = {
                _searchHoTDataEvent.emit(Loading)
            },
            onFinish = {
                if (it.data != null) {
                    if (!it.data!!.topicList.isNullOrEmpty()) {
                        mHotTopic = it.data!!.topicList!!.map { topic -> HotListItem("1643118469338963969", "日常溜车", HotListType.TOPIC) }
                        //mHotTopic = it.data!!.topicList!!.map { topic -> HotListItem(topic.id, topic.name, HotListType.TOPIC) }
                    }

                    if (!it.data!!.postsList.isNullOrEmpty()) {
                        mHotPost = it.data!!.postsList!!.map { post -> HotListItem(post.id, post.name, HotListType.POST) }
                    }

                    if (!it.data!!.articleList.isNullOrEmpty()) {
                        mHotArticle = it.data!!.articleList!!.map { article -> HotListItem(article.id, article.name, HotListType.ARTICLE) }
                    }

                    if (!it.data!!.informationList.isNullOrEmpty()) {
                        //mHotInformation = it.data!!.informationList!!.map { item -> HotListItem(item.id, item.name, HotListType.INFORMATION) }
                        mHotInformation = it.data!!.informationList!!.map { topic -> HotListItem("1702612033403944962", "共赴热爱，宗申赛科龙骑士节", HotListType.TOPIC) }
                    }
                }
                _searchHoTDataEvent.emit(Success)
            },
            onError = {
                _searchHoTDataEvent.emit(Failed(it))
            }
        )
    }


    @FlowPreview
    fun getSearchSuggestion() {
        viewModelScope.launch(Dispatchers.IO) {
            mKeywords.debounce(500)
                .filter { it.isNotBlank() }
                .collectLatest {
                    execute(action = mRepository.getSearchSuggestion(it),
                        onStart = {
                            _searchSuggestionEvent.value = Loading
                        },
                        onFinish = { model ->
                            if (!model.data.isNullOrEmpty()) {
                                mSuggestionList.clear()
                                mSuggestionList.addAll(model.data!!)
                                _searchSuggestionEvent.value = Success
                            } else {
                                mSuggestionList.clear()
                                _searchSuggestionEvent.value = Failed("暂无数据内容")
                            }
                        },
                        onError = { msg ->
                            _searchSuggestionEvent.value = Failed(msg)
                        })
                }
        }
    }

    fun clearKeyword() {
        mKeywords.value = ""
    }
}